#include "app_modbus.h"
#define DEVICE "/dev/ttyS1"
#define BAUD 115200
#define PARITY 'N'
#define DATA_BIT 8
#define STOP_BIT 1

static modbus_t *modbus;

GateState_t App_Modbus_Init(void)
{
    if (modbus)
    {
        return GATE_OK;
    }
    // 创建modbus
    modbus = modbus_new_rtu(DEVICE, 115200, PARITY, DATA_BIT, STOP_BIT);
    // 连接串口
    int res = modbus_connect(modbus);
    if (res == -1)
    {
        log_error("串口打开失败");
        modbus_free(modbus);
        return GATE_ERROR;
    }
    // 开启调试模式
    modbus_set_debug(modbus, true);
    log_info("modbus初始化成功");
    return GATE_OK;
}

GateState_t App_Modbus_Deinit(void)
{
    modbus_close(modbus);
    modbus_free(modbus);
}

// 写单个保持寄存器
GateState_t App_Modbus_WriteHodeRegister(uint8_t addr, uint16_t value)
{
    // 设置从机地址
    modbus_set_slave(modbus, addr);
    int res = modbus_write_register(modbus, 0, value);
    if (res == -1)
    {
        log_error("写保持寄存器失败");
        return GATE_ERROR;
    }
    return GATE_OK;
}

GateState_t App_Modbus_ReadInputRegister(uint8_t addr, uint16_t *value)
{
    // 设置从机地址
    modbus_set_slave(modbus, addr);
    int res = modbus_read_input_registers(modbus, 0, 1, value);
    if (res == -1)
    {
        log_error("读输入寄存器失败");
        return GATE_ERROR;
    }
    return GATE_OK;
}
